package com.liliudong.makabaka.controller.sys;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liliudong.makabaka.common.R;
import com.liliudong.makabaka.exception.BusinessException;
import com.liliudong.makabaka.sys.dto.SysUserLoginDTO;
import com.liliudong.makabaka.sys.entity.SysUser;
import com.liliudong.makabaka.sys.service.SysUserService;
import com.liliudong.makabaka.sys.vo.SysUserProfileVo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 用户控制器
 *
 * @author liudo
 * @version 1.0
 * @project makabaka-backend
 * @date 2023/9/23 16:41:59
 */
@RestController
@RequestMapping("/v1/sys-user")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService sysUserService;

    /**
     * 登录
     *
     * @param sysUserLoginDTO sys用户登录dto
     * @return {@link R}<{@link ?}>
     */
    @PostMapping("/login")
    public R<?> login(@RequestBody SysUserLoginDTO sysUserLoginDTO) {
        SysUser user = sysUserService.getOne(
                Wrappers.lambdaQuery(SysUser.class)
                        .select(SysUser::getId, SysUser::getPassword)
                        .eq(SysUser::getUsername, sysUserLoginDTO.getUsername())
        );
        if (Objects.isNull(user)) {
            throw new BusinessException("账号不存在");
        }
        if (!BCrypt.checkpw(sysUserLoginDTO.getPassword(), user.getPassword())) {
            throw new BusinessException("密码错误");
        }
        StpUtil.login(user.getId(), sysUserLoginDTO.getRememberMe());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return R.success(tokenInfo);
    }

    /**
     * 退出登录
     *
     * @return {@link R}<{@link ?}>
     */
    @SaCheckLogin
    @GetMapping("/logout")
    public R<?> logout() {
        StpUtil.logout();
        return R.success();
    }

    /**
     * 用户资料
     *
     * @return {@link R}<{@link SysUserProfileVo}>
     */
    @SaCheckLogin
    @GetMapping("/profile")
    public R<SysUserProfileVo> profile() {
        SysUserProfileVo sysUserProfileVo = sysUserService.profile();
        return R.success(sysUserProfileVo);
    }
}
